package util;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONObject;

import exception.HTTPClientException;

/**
 * @author LCY
 *
 */
public class KKClient {
    
    /**
     * sendPOSTRequest(发送post请求)
     * (这里描述这个方法适用条件 – 可选)
     * @param url
     * @param token
     * @param obj
     * @return
     * @throws Exception
     *JSONObject
     * @exception
     * @since  1.0.0
    */
    @SuppressWarnings("deprecation")
	public static JSONObject sendPOSTRequest(String url,String token,JSONObject obj) throws Exception {
    	String result = "";
    	try{
    		//1.创建http链接对象
        	CloseableHttpClient httpclient = HttpClients.createDefault(); 
        	httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
            HttpPost httppost = new HttpPost(url); 
            //2.封装键值对
            List<NameValuePair> formparams = getKeyValuePostOneParameter(obj,token);  
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
            httppost.setEntity(uefEntity);  
            //3.发送请求
            System.out.println("executing request " + httppost.getURI());  
            CloseableHttpResponse response = httpclient.execute(httppost); 
            //5.获取结果 
            HttpEntity entity = response.getEntity(); 
            if (entity != null) {  
                result = EntityUtils.toString(entity, "UTF-8");
                JSONObject temp = new JSONObject();
                temp = JSONObject.parseObject(result);
                if(!CommonConstant.STATUS_SUCCESS.equals(temp.get("code"))){
    				throw new HTTPClientException(temp.getString("code"),temp.getString("message"));
    			}
            }
            //5.关闭连接
            response.close();  
            httpclient.close();  
    	}catch(Exception e){   
			if(e instanceof org.apache.http.NoHttpResponseException) {
				throw new HTTPClientException("408","服务器链接超时");
			}else{
				throw new HTTPClientException("500","服务器未知错误");
			}
		}
    	//6.返回结果
        return JSONObject.parseObject(result);
    }
    
    public static JSONObject sendGETRequest(String url,String token,JSONObject obj) throws Exception {
    	//1.创建http链接对象
    	CloseableHttpClient httpclient = HttpClients.createDefault();  
        //2.生成getUrl
        String getUrl = getKeyValueGet(url,obj,token);  
        HttpGet httpget = new HttpGet(getUrl);  
        //3.发送请求
        System.out.println("executing request " + httpget.getURI());  
        CloseableHttpResponse response = httpclient.execute(httpget);  
        //4.获取结果 
        HttpEntity entity = response.getEntity();  
        String result = "";
        if (entity != null) {  
            result = EntityUtils.toString(entity, "UTF-8");
        }
        //5.关闭连接
        response.close();  
        httpclient.close();  
        //6.返回结果
        return JSONObject.parseObject(result);
    }
    
    /**
     * getKeyValuePost(将JSONObject转换为键值对)
     * @param obj
     * @return
     *List<NameValuePair>
     * @exception
     * @since  1.0.0
    */
	private static List<NameValuePair> getKeyValuePost(JSONObject obj,String token) {
    	List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
    	if(!ValidationUtil.isEmpty(obj)) {
    		Set<String> keys = obj.keySet();
            for (String key : keys) {
            	formparams.add(new BasicNameValuePair(key, obj.getString(key)));  
    		}
            if(!StringUtils.isEmpty(token)){
            	formparams.add(new BasicNameValuePair("token", token)); 
            }
    	}
        return formparams;
    }
    
    /**
     * getKeyValuePost(将JSONObject转换为json串,用data作为键值)
     * {
     *    data:{
     *       name:'lcy'
     *       age:24
     *    }
     * }
     * @param obj
     * @return
     *List<NameValuePair>
     * @exception
     * @since  1.0.0
    */
    private static List<NameValuePair> getKeyValuePostOneParameter(JSONObject obj,String token) {
    	List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
    	if(!ValidationUtil.isEmpty(obj)) {
            formparams.add(new BasicNameValuePair("data", obj.toJSONString()));  
    	}
        if(!ValidationUtil.isEmpty(token)){
        	formparams.add(new BasicNameValuePair("token", token)); 
        }

        return formparams;
    }
    
    /**
     * getKeyValueGet(将JSONObject转换为键值对)
     * (这里描述这个方法适用条件 – 可选)
     * @param obj
     * @param token
     * @return
     *List<NameValuePair>
     * @exception
     * @since  1.0.0
    */
    private static  String getKeyValueGet(String url,JSONObject obj,String token) throws Exception{
    	String uri = "?";
    	if(!ValidationUtil.isEmpty(obj)) {
    		Set<String> keys = obj.keySet();
            for (String key : keys) {
            	uri += key + "=" + obj.getString(key) + "&";
    		}
    	}
    	uri += "token=" + token;
    	return url+uri;
    }
}
